# coding=utf-8
from abc import ABCMeta
import tornado.web
import tornado.escape
import json

from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.Normal import Normal
import WrapCursor


class GetNormalFlowHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        ojson = None
        r = WrapCursor.WrapCursor()
        id = None
        try:
            ojson = json.loads(self.request.body)
            desc = ojson['id']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except:
            self.write(r.Error(u'检查请求数据'))
            return
        nid = ojson['id']
        filt = {'IsAdvance': 0}
        if nid == -1:
            sql = """
                select * from normalstep where IsAdvance=0
            """
        else:
            sql = """
                select * from normalstep where IsAdvance=0
                                               and id == ?
            """
            filt['id'] = nid

        s = Session()
        ns = s.query(Normal).filter_by(**filt).all()
        jsonret = dict()
        jsonret['data'] = list()
        jsonret['Code'] = 0
        jsonret['desc'] = u'成功'
        for n in ns:
            o = dict()
            o['Desc'] = n.desc
            o['ID'] = n.id
            o['Name'] = n.name
            jsonret['data'].append(o)
        self.write(json.dumps(jsonret))
        return
